//
//  MineViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/9/28.
//  Copyright © 2020 吴欧. All rights reserved.
//

#import "MineViewController.h"
#import "HEMineHeadView.h"
#import "HEMineRecordCell.h"
#import "HEMineOrderCell.h"
#import "HEMineServiceCell.h"
#import "HECartViewController.h"
#import "HEOrderViewController.h"
#import "HESettingViewController.h"
#import "HEAfterListViewController.h"
#import "HEMyDoctorViewController.h"
#import "HEMyReportViewController.h"
#import "HEMyReportReadViewController.h"
#import "HETWRecodViewController.h"
#import "HEMyApplyViewController.h"
#import "HEMyServiceViewController.h"
#import "HEReagentCheckViewController.h"
#import "HEHealthPlaneController.h"
#import "HEHealthArchiveModel.h"
#import "HEAssesReportViewController.h"
#import "HEMyCollectViewController.h"
#import "HEHealthNoticeViewController.h"
#import "HEAbourtViewController.h"
#import "HESuggestViewController.h"
#import "HEBindUserModel.h"
#import "HEBindListViewController.h"
#import "HEMyDocTeamViewController.h"
#import "HEMyActiveViewController.h"
#import "HEAddressViewController.h"

@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource, HEMineOrderCellDelegate, HEMineServiceCellDelegate>
 
@property (nonatomic, strong) NSArray *setsArray;
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSString *userIdCrad;
@property (nonatomic, strong) NSMutableArray <HEBindUserModel *> *bindUsers;

@end

@implementation MineViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"个人中心";
    self.tabBarItem.title = @"我的";
    [self setupNav];
    
    [self initUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:KChangeFontNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadHealthRecodeData) name:KNotificationRealAuth object:nil];

    [self loadHealthRecodeData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KChangeFontNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name: KNotificationRealAuth object:nil];
}

- (void)refresh {
    [self.tableView reloadData];
}

- (void)setupNav {
    self.zx_navBar.backgroundColor = CNavLightBlackColor;
    self.zx_navLineView.hidden = YES;
    self.zx_navTitleColor = KWhiteColor;
    self.zx_navStatusBarStyle = ZXNavStatusBarStyleLight;
}

- (void)initUI {
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight -kTabBarHeight) style:UITableViewStyleGrouped];
    _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0); 
            
    //        //头部刷新
    //        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    //        header.automaticallyChangeAlpha = YES;
    //        header.lastUpdatedTimeLabel.hidden = YES;
    //        _tableView.mj_header = header;
    //
    //        //底部刷新
    //        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
    ////        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);
    ////        _tableView.mj_footer.ignoredScrollViewContentInsetBottom = 30;

    _tableView.scrollsToTop = YES;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = CViewBgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];

 
    [self.tableView registerClass:[HEMineRecordCell class] forCellReuseIdentifier:@"HEMineRecordCell"]; 
    [self.tableView registerClass:[HEMineOrderCell class] forCellReuseIdentifier:@"HEMineOrderCell"];
    [self.tableView registerClass:[HEMineServiceCell class] forCellReuseIdentifier:@"HEMineServiceCell"];

    HEMineHeadView *headView = [[HEMineHeadView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 210)];
    headView.vc = self;
    self.tableView.tableHeaderView = headView;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 50)];
    
    [self.tableView setSeparatorColor: [UIColor colorWithHexString:@"#EEEEEE"]]; //cell分割线的颜色

}

#pragma mark - 
- (void)loadHealthRecodeData {
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetPhrUserInfo parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [UserManager sharedUserManager].archiveInfo = [HEHealthArchiveModel mj_objectWithKeyValues: response.data];
            [self getBindUserData];
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)getBindUserData {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[UserManager sharedUserManager].curUserInfo.id forKey:@"gid"];
    
    KWeakSelf
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KgetBindUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        [self.bindUsers removeAllObjects];
        [weakSelf.bindUsers addObjectsFromArray:[HEBindUserModel mj_objectArrayWithKeyValuesArray:response.data]];
        HEHealthArchiveModel *archiveInfo = [UserManager sharedUserManager].archiveInfo;
        BOOL hasOwn = NO;
        for (HEBindUserModel *model in weakSelf.bindUsers) {
            if ([archiveInfo.usid isEqual:model.id]) {
                hasOwn = YES;
                break;
            }
        }
        if (!hasOwn && [UserManager sharedUserManager].curUserInfo.verifyStatus) {
            HEBindUserModel *ower = [HEBindUserModel new];
            ower.id = archiveInfo.usid;
            ower.realname = archiveInfo.xm;
            ower.relations = @"本人";
            ower.birth_date = archiveInfo.csrq;
            ower.pid = archiveInfo.pid;
            ower.sex = [HEEnums sexToCode:archiveInfo.xbmc];
            [weakSelf.bindUsers insertObject:ower atIndex:0];
        }
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
        case 1:
        case 2:
            return 1;
            break;
        case 3:
            return self.setsArray.count;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
        {
            HEMineRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEMineRecordCell"];
            cell.vc = self;
            [cell refreshUserInfo:self.bindUsers];
            return cell;
        }
        case 1:
       {
           HEMineOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEMineOrderCell"];
           cell.delegate = self;
           return cell;
       }
        case 2:
      {
          HEMineServiceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HEMineServiceCell"];
          cell.delegate = self;
          return cell;
      }
        case 3:
      {
          UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
          if (cell == nil) {
              cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
              cell.textLabel.font = DYFont(18);
              cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
              cell.selectionStyle = UITableViewCellSelectionStyleNone;
          }
          
          cell.textLabel.text = _setsArray[indexPath.row];
          
          return cell;
      }
        default:
            break;
    }

    return nil;
}

#pragma mark -

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 15)];
    v.backgroundColor = CViewBgColor;
    return v;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
          return 145;
        case 1:
        case 2:
          return 125;
        default:
            break;
    }
    return 47;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 3:
            [self selectSetting:indexPath.row];
            break;
            
        default:
            break;
    }
}

- (void)selectSetting:(NSInteger)row {
    switch (row) {
        case 0: {
            HEBindListViewController *vc = [HEBindListViewController new];
            vc.backBlock = ^{
                [self loadHealthRecodeData];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 1: {
            HEAssesReportViewController *vc = [HEAssesReportViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 2: {
            HEHealthNoticeViewController *vc = [HEHealthNoticeViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3: {
            HEMyActiveViewController *vc = [HEMyActiveViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 4: {
            HEMyCollectViewController *vc = [HEMyCollectViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 5: {
            HESuggestViewController *vc = [HESuggestViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        case 6:
        {
            HEAbourtViewController *vc = [HEAbourtViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 7: {
            HEAddressViewController *vc = [HEAddressViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 8: {
            HESettingViewController *vc = [HESettingViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark 解决cell分割线左侧留空的问题
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 下面这几行代码是用来设置cell的上下行线的位置
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 15, 0, 0)];
    }
    
    //按照作者最后的意思还要加上下面这一段，才能做到底部线控制位置，所以这里按stackflow上的做法添加上吧。
    if([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]){
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
}

- (NSArray *)setsArray {
    if (!_setsArray) {
        _setsArray = @[@"我家老人",@"健康评估",@"健康提醒" , @"我的活动", @"我的收藏",@"帮助与反馈", @"关于", @"地址管理",@"设置"];
//        _setsArray = @[@"健康评估",@"健康提醒", @"我的活动", @"我的收藏",@"帮助与反馈", @"关于", @"设置"];

    }
    return _setsArray;
}

#pragma mark - HEMineOrderCellDelegate
- (void)mineOrderDidSelectAtIndex:(NSInteger)index {
    switch (index) {
        case 0: {
            [self productJump];
//            HECartViewController *vc = [HECartViewController new];
//            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 6: {
            HEAfterListViewController *vc = [HEAfterListViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
            
        default: {
            HEOrderViewController *vc = [HEOrderViewController new];
            vc.index = index-1;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
    }
}

#pragma mark -
- (void)productJump {
    if (self.userIdCrad != NULL) {
        [self intoWxminiServer];
        return;
    }
     
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KuserSfz parameters:@{} success:^(id  _Nonnull responseObject) {
        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            self.userIdCrad = response.data;
            [self intoWxminiServer];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

- (void)intoWxminiServer {
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];

    NSMutableDictionary *patientData = [NSMutableDictionary dictionary];
    [patientData setValue:user.id forKey:@"id"];
    [patientData setValue:user.username forKey:@"phone"];
    [patientData setValue:[NSNumber numberWithInteger:user.sex] forKey:@"sex"];
    [patientData setValue:user.realname forKey:@"userName"];
    [patientData setValue:self.userIdCrad forKey:@"idCard"];

    [params setValue:patientData forKey:@"patientData"];

    NSString *encodeData = [[params mj_JSONString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    encodeData = [[params mj_JSONString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *path = [NSString stringWithFormat:@"%@%@%@", @"packageA/pages/oderForm/main" , @"?source=app&query=", encodeData];
    if ([WXApi isWXAppInstalled]) { //先判断是否安装微信
        WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
        launchMiniProgramReq.userName = @"gh_8a6c24d3e9b4";  //拉起的小程序的username-原始ID
    launchMiniProgramReq.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        if (!success) {
            [Dialog toastBottom:@"无法唤起小程序"];
        }
    }];
    }else{
        //提示用户没有安装微信，不能拉起小程序
    }
    
}

#pragma mark - HEMineServiceCellDelegate
- (void)mineServerDidSelectAtIndex:(NSInteger)index {
    switch (index) {
        case 0: {
            HEMyDoctorViewController *vc = [HEMyDoctorViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 1: {
            HEMyDocTeamViewController *vc = [HEMyDocTeamViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 2: {
            HETWRecodViewController *vc = [HETWRecodViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 3: {
            HEMyApplyViewController *vc = [HEMyApplyViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 4: {
            HEHealthPlaneController *vc = [HEHealthPlaneController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 5: {
            HEMyReportReadViewController *vc = [HEMyReportReadViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 6: {
            HEMyServiceViewController *vc = [HEMyServiceViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 7: {
            HEMyReportViewController *vc = [HEMyReportViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
        case 8: {
            HEReagentCheckViewController *vc = [HEReagentCheckViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        }
        break;
            
            
        default: {
        }
            break;
    }
}

#pragma mark -
- (NSMutableArray<HEBindUserModel *> *)bindUsers {
    if (!_bindUsers) {
        _bindUsers = @[].mutableCopy;
    }
    return _bindUsers;
}

@end
